package com.rlz.base.util

import android.os.Handler
import android.os.Looper
import android.os.Process
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * Created by RLZ
 * on 2021/5/17
 *
 */
class ThreadUtil {

    companion object {

        private var mThreadPool = getThreadPool()

        private var mHandler: Handler? = null

        /**
         * 在子线程执行任务
         */
        @JvmStatic
        fun runInThread(task: Runnable?) {
            mThreadPool!!.execute(task)
        }

        /**
         * 清理线程中的问题;
         */
        @JvmStatic
        fun cancelThread(task: Runnable?) {
            mThreadPool!!.cancel(task)
        }

        /**
         * 判断当前是否在主线程运行
         */
        @JvmStatic
        fun isRunOnUiThread(): Boolean =
                Process.myTid().toLong() == getMainThreadId()

        private fun getMainThreadId(): Long =
                Looper.getMainLooper().thread.id


        /**
         * 在UI线程执行任务
         */
        @JvmStatic
        fun runOnUiThread(task: Runnable?) {
            mHandler!!.post(task!!)
        }


        /**
         * 在UI线程延时执行任务
         *
         */
        @JvmStatic
        fun runOnUiThread(task: Runnable?, delayMillis: Long) {
            mHandler!!.postDelayed(task!!, delayMillis)
        }


        /**
         * 获取单例的线程池对象
         */
        @JvmStatic
        fun getThreadPool(): ThreadPool {
            if (mThreadPool == null) {
                synchronized(ThreadUtil::class.java) {
                    if (mThreadPool == null) {
                        val cpuNum = Runtime.getRuntime().availableProcessors()
                        val count = cpuNum * 2 + 1
                        //var count = 15;
                        println("cpu个数:$cpuNum")
                        mThreadPool = ThreadPool(count, count, 0L)
                        mHandler = Handler(Looper.getMainLooper())
                    }
                }
            }
            return mThreadPool
        }
    }


    class ThreadPool constructor(// 核心线程数
            private val corePoolSize: Int, // 最大线程数
            private val maximumPoolSize: Int, // 保持活跃时间(休息时间)
            private val keepAliveTime: Long) {
        private var executor: ThreadPoolExecutor? = null
        fun execute(r: Runnable?) {
            if (executor == null) {
                executor = ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, LinkedBlockingDeque(),
                        Executors.defaultThreadFactory(), ThreadPoolExecutor.AbortPolicy())
            }
            executor!!.execute(r) // 将当前Runnable对象放在线程池中
        }

        fun cancel(r: Runnable?) {
            if (executor != null) {
                executor!!.queue.remove(r)
            }
        }
    }
}